package struts.action;

import javax.naming.InitialContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import struts.actionform.ClientLoginForm;
import ejb.bl.CartBeanRemote;
import ejb.bl.MusicStoreBLRemote;

public class ClientLoginAction extends Action {

	
	//@EJB(name = "CartBean")	
	private CartBeanRemote CartBean;
	private MusicStoreBLRemote MusicStoreBLBean;
    
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HttpSession session = request.getSession();
		InitialContext ic=null;
		// Create object of ActionMesssages
		ActionMessages errors = new ActionMessages();

		// creating object of UserLoginForm
		ClientLoginForm objForm = (ClientLoginForm) form;

		// get userid from objForm
		int userid = objForm.getUserid();

		// get password from objForm
		String strPassword = objForm.getPassword();

		// check user is valid or not
		try {
			if(session.getAttribute("sessionContext")==null){
				ic = new InitialContext();
				session.setAttribute("sessionContext",ic);
			}else{
				ic =(InitialContext)session.getAttribute("sessionContext");
			}
			MusicStoreBLBean = (MusicStoreBLRemote) ic
					.lookup("java:global/IMusicStore/MusicStoreStalessBean");
			boolean loginStatus = MusicStoreBLBean.checkClientLogin(userid,
					strPassword);

			if (loginStatus == true) {
				// create new session object
				session.setAttribute("UserID", String.format("%d", userid));				
				CartBean =(CartBeanRemote) ic
						.lookup("java:global/IMusicStore/CartBean");
				CartBean.initialize(userid);	
				session.setAttribute("CartBean", CartBean);
				return mapping.findForward("success");
			} else {
				errors.add("login", new ActionMessage("error.login.invalid"));
				// saving error object
				saveErrors(request, errors);

				return mapping.findForward("fail");
			}
		} catch (RuntimeException e) {
			throw e;
		}
	}
}
